/**
 * @file PictureState.cpp
 *
 * @date 19/12/2011
 * @author Tales 
 *
 */

#include "PictureState.hpp"
#include "../common/Error.hpp"

namespace yep
{

PictureState::PictureState()
{
}

PictureState::PictureState(Uint16 w, Uint16 h, Uint8 bpp)
{
	this->bpp = bpp;
	this->w = w;
	this->h = h;
	addLayer();
}

PictureState::~PictureState()
{
}

Uint8 PictureState::getBpp() const
{
	return bpp;
}

Uint16 PictureState::getH() const
{
	return h;
}

Uint16 PictureState::getW() const
{
	return w;
}

void PictureState::setBpp(Uint8 bpp)
{
	this->bpp = bpp;
}

void PictureState::setH(Uint16 h)
{
	this->h = h;
}

void PictureState::addLayer(SDL_Surface *surface)
{
	YEP_ASSERT(surface != NULL);
	YEP_ERROR_TEST(surface->w == w && surface->h == h &&surface->format->BitsPerPixel == bpp, "Layer format error");
	size_t index = layers.size();
	layers.resize(index + 1);
	layers[index].setSurface(surface);
}

void PictureState::removeLayer(size_t qtd)
{
	YEP_ASSERT(layers.size()>=qtd);
	layers.erase(layers.end() - qtd, layers.end());
}

void PictureState::swap(size_t l1, size_t l2)
{
	YEP_ASSERT(l1 < layers.size());
	YEP_ASSERT(l2 < layers.size());
	Layer &layer1 = layers[l1];
	Layer &layer2 = layers[l2];
	SDL_Surface *toL2Surface = layer1.getSurface();
	toL2Surface->refcount++;
	SDL_Surface *toL1Surface = layer2.getSurface();
	toL1Surface->refcount++;
	layer1.setSurface(toL1Surface);
	layer2.setSurface(toL2Surface);
}

void PictureState::setW(Uint16 w)
{
	this->w = w;
}

Layer & PictureState::getLayer(size_t index)
{
	return layers[index];
}

size_t PictureState::getLayerCount()
{
	return layers.size();
}

void PictureState::addLayer()
{
	size_t index = layers.size();
	layers.resize(index + 1);
	Uint32 rmask, gmask, bmask, amask = (bpp == 32 ? 0xff000000 : 0);
	switch (bpp)
	{
	case 8:
	case 24:
	case 32:
		rmask = 0xff0000;
		gmask = 0x00ff00;
		bmask = 0x0000ff;
		break;
	case 15:
		rmask = 0x7c00;
		gmask = 0x03e0;
		bmask = 0x001f;
		break;
	case 16:
		rmask = 0xf800;
		gmask = 0x07e0;
		bmask = 0x001f;
		break;
	default:
		break;
	}
	SDL_Surface *surface = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, rmask, gmask, bmask, amask);
	layers[index].setSurface(surface);
	SDL_FillRect(surface, NULL, SDL_MapRGBA(surface->format, 255, 255, 255, 0));
	if (bpp < 32)
		SDL_SetColorKey(surface, SDL_SRCCOLORKEY, 0x00FFffFF);

}
} /* namespace yep */
